package org.airlink.persistence
{
	import flash.data.SQLConnection;
	import flash.data.SQLResult;
	import flash.data.SQLStatement;
	
	import flex.persistence.EntityTransaction;
	import flex.persistence.FlushModeType;
	import flex.persistence.Query;
	import flex.persistence.criteria.AbstractQuery;
	
	import mx.utils.ObjectUtil;
	import mx.utils.StringUtil;

	public class QueryImpl implements Query
	{		
		
		private var resultClass:Class;
		private var isSimple:Boolean = false;
		protected var query:String;
		protected var entityManager:EntityManagerImpl;
		protected var transaction:EntityTransaction;
		
		
		
		public function QueryImpl(resultClass:Class, entityManager:EntityManagerImpl, query:String, transaction:EntityTransaction=null) {
			this.entityManager = entityManager;
			if(!transaction) transaction = entityManager.getTransaction();
			this.transaction = transaction;
			this.resultClass = resultClass;
			if(resultClass) {
				isSimple = ObjectUtil.isSimple(new resultClass());
			}
			this.query = query;
		}
			
			
			public function executeUpdate():int{
				return 0;
			}
			
			public function getResultList():Array {
				return null;
			}
			
			
			public function getSql():String{
				return this.query;
			}
			
			                     
					 
			   
			public function getSingleResult():Object{
				var statement:SQLStatement = new SQLStatement();
				transaction.begin();
				statement.sqlConnection = transaction.dbConnection as SQLConnection;
			
				//statement.text = query; 
			
				statement.execute();
				var sqlResult:SQLResult = statement.getResult();
				var resultsSql:Array = sqlResult.data;
				var results:Array = new Array();
				for each(var result:Object in resultsSql) {
					results.push(transformResult(result));
				}
				transaction.commit();
				return results;
				
			}
			
			
			public function setFirstResult(startPosition:int):Query {
				return null;
			}
			
			public function setFlushMode(flushMode:FlushModeType):Query {
				return null;
			}
			
			public function setHint(hintName:String, value:Object):Query {
				return null;
			}
			
			public function setMaxResults(maxResult:int):Query {
				return null;
			}
			
			public function setParameterByIndex(position:int, value:Object):Query {
				return null;
			}				
			
			public function setParameterByName(name:String, value:Object):Query {
				return null;
			}
			
			private function transformResult(object:Object):* {
				var result:*;
				if(isSimple) {
					var str:String = StringUtil.trim(ObjectUtil.toString(object).split("=")[1]);
					result = resultClass(str);
				} else {
					var entity:Entity = entityManager.introspector.loadMetadata(resultClass);
					var id:Object = object[entity.idField.columnName];
					
					result = entityManager.find(resultClass, id, transaction); 
				}
				return result;
			}
			
		}
	}